package org.scboy.rbac.service.imp;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.rbac.dao.RbacResourceRoleTypeDao;
import org.scboy.rbac.service.ResourceRoleTypeService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class ResourceRoleTypeServiceImp implements ResourceRoleTypeService {

	@Autowired
	EntityFactory factory;
	
	@Override
	@Transactional
	public boolean addResource(String code, String[] resId) {
		RbacResourceRoleTypeDao dao=factory.getDao(RbacResourceRoleTypeDao.class);
		//删除掉原有的关联
		dao.delete(Model.create().add("code", code));
		//增加新的关联
		if(resId!=null){
			for (String rid : resId) {
				Model roleJobType=new Model();
				roleJobType.add("id", UUID.randomUUID().toString());
				roleJobType.add("resId", rid);
				roleJobType.add("code", code);
				roleJobType.add("addTime", new Date());
				roleJobType.add("editTime", new Date());
				dao.insert(roleJobType);
			}
		}
		return true;
	}

	@Override
	public boolean delete(String id) {
		RbacResourceRoleTypeDao dao=factory.getDao(RbacResourceRoleTypeDao.class);
		int result=dao.delete(Model.create().add("id", id));
		if(result>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Page page(Model params) {
		RbacResourceRoleTypeDao dao=factory.getDao(RbacResourceRoleTypeDao.class);
		return dao.queryPage(params);
	}

	@Override
	public String[] getResIds(String code) {
		RbacResourceRoleTypeDao dao=factory.getDao(RbacResourceRoleTypeDao.class);
		List<Model> result=dao.select(Model.create().add("code", code));
		String [] resIds=new String [result.size()];
		for (int i = 0; i < result.size(); i++) {
			resIds[i]=result.get(i).getString("resId");
		}
		return resIds;
	}
	
}
